package com.hz.sys.utils;
import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.hz.sys.config.AlPayConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author mcz
 * @Date 2018/9/30 15:20
 * @Description
 * @Version 1.0
 */
public class WebUtil {
    private static   Logger logger=LoggerFactory.getLogger(WebUtil.class);
     /**
      * @Description
      * @Date 2018/10/29 13:47
      * @Param 
      * @return 
      **/
   public   static  HttpServletRequest getRequest(){
       //两个方法在没有使用JSF的项目中是没有区别的
       RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
       return  ((ServletRequestAttributes)requestAttributes).getRequest();
   }

    public    static  HttpServletResponse getResponse(){
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes.getResponse();
    }

    public static String getBasePath(){
        HttpServletRequest request=getRequest();
        StringBuffer buffer=new StringBuffer();
        buffer.append(request.getScheme());
        buffer.append("://");
        buffer.append(request.getServerName());
        buffer.append(":");
        buffer.append(request.getServerPort());
        buffer.append("/");
        return buffer.toString();
    }

     /**
      * @Description  判断是否为ajax请求
      * @Date 2018/10/29 13:50
      * @Param
      * @return
      **/
    public   static  boolean isAjaxRequest(){
       boolean result=false;
        String requestType = getRequest().getHeader("X-Requested-With");
        if("XMLHttpRequest".equals(requestType)){
            result=true;
        }
        return result;
    }
    /**
     * 创建日期:2018年4月6日<br/>
     * 代码创建:mcz<br/>
     *  描述:返回json数据<br/>
     * @param resp
     * @param jsonString
     */
    public  static  void writeJson(HttpServletResponse resp ,String jsonString ){
        PrintWriter out = null;
        try {
            //设定类容为json的格式
            resp.setContentType("application/json;charset=UTF-8");
            out = resp.getWriter();
            //写到客户端
            out.write(jsonString);
            out.flush();
        } catch (IOException e) {
            logger.error("输出json字符串异常{}",e.getMessage());
        } finally {
            if(out != null){
                out.close();
            }
        }
    }

    /**
     * 支付宝接口回调校验sign是否正确
     * @param request
     * @return
     */
    public static boolean isSign(HttpServletRequest request){
        Map<String,String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            try {
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            params.put(name, valueStr);
        }
        String sign = request.getParameter("sign");
        boolean result = false;
        if(params.size() > 0){
            try {
                result = AlipaySignature.rsaCheckV1(params, AlPayConfig.ALI_PAY_PUBLIC_KEY, "UTF-8","RSA2");
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
        }
        return result;
    }




}
